package com.denley.preferencebinder.sample;

import me.denley.preferencebinder.BindPref;
import me.denley.preferencebinder.PreferenceBinder;
import me.denley.preferencebinder.internal.WidgetBindingType;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Checkbox;
import ohos.agp.components.Slider;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
/**
 * use in Ability
 */
public class MainAbility extends Ability {
    private static final long PREFERENCE_CHANGE_INTERVAL_MS = 500;
    private static final long PREFERENCE_CHANGE_INITIAL_WAIT_MS = 3000;

    @BindPref(value = "boolean_pref_key", bindTo = WidgetBindingType.CHECKED)
    Checkbox booleanPreferenceDisplay;

    @BindPref(value = "integer_pref_key", bindTo = WidgetBindingType.SLIDER_PROGRESS)
    Slider integerPreferenceDisplay;

    @BindPref(value = "boolean_pref_key", listen = true)
    boolean booleanPrefValue;

    private EventHandler handler;

    Runnable externalPreferenceChanger = new Runnable() {
        @Override
        public void run() {
            changePreferenceValues();
            handler.postTask(externalPreferenceChanger, PREFERENCE_CHANGE_INTERVAL_MS);
        }
    };

    @BindPref(value = {"integer_pref_key", "boolean_pref_key"}, init = false)
    void onNewValue3() {

    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        booleanPreferenceDisplay = (Checkbox) findComponentById(ResourceTable.Id_pref_boolean);
        integerPreferenceDisplay = (Slider) findComponentById(ResourceTable.Id_pref_integer);
        PreferenceBinder.bind(this);
        startHandler();
    }

    private void startHandler(){
        handler = new EventHandler(EventRunner.getMainEventRunner());
        handler.postTask(externalPreferenceChanger, PREFERENCE_CHANGE_INITIAL_WAIT_MS);
    }

    private void changePreferenceValues(){
        final Preferences prefs = new DatabaseHelper(this).getPreferences("default");
        final boolean booleanPrefValue = !prefs.getBoolean("boolean_pref_key", false);
        final int integerPrefValue = (prefs.getInt("integer_pref_key", 0) + 1) % 100;
        prefs.putBoolean("boolean_pref_key", booleanPrefValue)
                .putInt("integer_pref_key", integerPrefValue)
                .flush();
    }

    @Override
    protected void onStop() {
        PreferenceBinder.unbind(this);
        handler.removeTask(externalPreferenceChanger);
        super.onStop();
    }
}
